import { Component, Inject, ViewChildren, ViewChild, ChangeDetectorRef  } from '@angular/core';
import { IonicPage, ViewController, Content } from 'ionic-angular';
import { Subscription } from 'rxjs/Subscription';

// service

/*** 电话联系人
 */
@IonicPage()
@Component({
  selector: 'page-contcats',
  templateUrl: 'contcats.html',
})
export class ContcatsPage {

  index: string; // 初始侧边激活
  indexes: Array<string>; // 侧边栏数组
  showModal: boolean = false; // 显示modal
  timeout: any;
  offsetTops: Array<number> = [];

  @ViewChildren('IonItemGroup') ionItemGroup;
  @ViewChild(Content) content: Content;
  // 处理的联系人列表
  formatContacts: Array<any>;
  contactsSubscription: Subscription;
  constructor(
    public viewCtrl: ViewController,
    @Inject('auth') private authService,
    public ref: ChangeDetectorRef,
  )
  {
  }
  ionViewDidLoad(){
    // this.contcatsService.getLocalTestList();
    // this.contcatsService.getContcatsList();

    this.contactsSubscription = this.authService.getContacts()
      .filter(data=> data.length>0)
      .subscribe(data=> {
      this.forEachIndexs(data);
      this.formatContacts= [...data];
    });
  }
  /*** 遍历得到indexes
   * @param data 联系人数组
  * */
  forEachIndexs(data: Array<any>)
  {
    let indexes= new Set();
    data.forEach(value=>{
      indexes.add(value.key);
    });
    this.index= Array.from(indexes)[0] || '';
    this.indexes= Array.from(indexes);
  }
  ionViewDidEnter() {
    this.getOffsetTops();
  }

  getOffsetTops() {
    this.offsetTops = this.ionItemGroup._results.map(ele => {
      return ele.nativeElement.offsetTop
    })
  }

  selectIndex(index: number) {
    this.index = this.indexes[index];
    const offsetTop = this.offsetTops[index];
    this.content.scrollTo(0, offsetTop, 300);
    this.createModal();
  }


  onScroll() {

    const threshold = 42;

    if (this.content.scrollTop < threshold) {
      this.index = this.indexes[0];
      this.ref.detectChanges();
      return;
    }

    for (let i = this.offsetTops.length; i > 0; i--) {
      if (this.content.scrollTop + threshold >= this.offsetTops[i]) {
        this.index = this.indexes[i];
        this.ref.detectChanges();
        return;
      }
    }
  }

  createModal() {
    clearTimeout(this.timeout);
    this.showModal = true;
    this.timeout = setTimeout(() => {
      this.showModal = false;
      this.ref.detectChanges();
    }, 800)
  }

  /*** 用户点击事件
   * @param item 得到选择的信息
   * */
  handleClick(item) {
    // alert(JSON.stringify(item));
    this.removeSubscription();
    this.viewCtrl.dismiss(item);
  }

  /*** 移除监听
   * */
  private removeSubscription(): void
  {
    if(typeof this.contactsSubscription !== 'undefined')
      this.contactsSubscription.unsubscribe();
  }

}
